<template>
  <div>
    <el-card>
      <el-row>
        <el-col :span="20">
          <el-input v-model="searchModel.username" placeholder="用户名" style="width: 180px" clearable></el-input>
          <el-input v-model="searchModel.phone" placeholder="电话" style="width: 180px" clearable></el-input>
          <el-button type="primary" round icon="el-icon-search" @click="search()">
            搜索
          </el-button>
        </el-col>
        <el-col :span="4" align="right">
          <el-button type="primary" icon="el-icon-plus" circle @click="editUserForm(null)"></el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <el-table
        :data="userList"
        stripe
        style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==1">正常</el-tag>
            <el-tag v-else type="danger">异常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" circle
                       @click="editUserForm(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" circle
                       @click="deleteUserById(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchModel.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog @close="closeUserForm()" :title="title" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" :model="userForm" ref="userForm">
        <el-form-item label="用户名" prop="username" label-width="180px">
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="180px" v-if="title === '新增用户'">
          <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="180px">
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email" label-width="180px">
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="180px">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="角色" label-width="180px">
          <el-checkbox-group
            v-model="userForm.roleIds"
            :min="1"
            :max="2">
            <el-checkbox v-for="role in roleList" :label="role.roleId" :key="role.roleId">{{role.roleDesc}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import userApi from '@/api/userApi'
import roleApi from '@/api/roleApi'

export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var reg =
        /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (!reg.test(value)) {
        return callback(new Error('邮箱格式错误'));
      }
      callback();
    };

    return {
      roleList: [],
      dialogFormVisible: false,
      userForm: {
        roleIds: [],
      },
      title: "",

      total: 0,
      searchModel: {
        username: "",
        phone: "",
        pageNo: 1,
        pageSize: 5,
      },
      userList: [],

      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    saveUser() {
      this.$refs.userForm.validate((vaild) => {
        if (vaild) {
          userApi.saveUser(this.userForm).then(resp => {
            this.$message({
              message: resp.message,
              type: 'success'
            })
            this.dialogFormVisible = false;
            this.getUserList()
          })
        } else {
          this.$message.error('验证失败');
        }
      })
    },
    closeUserForm() {
      this.userForm = {
        roleIds: [],
      }
      this.$refs.userForm.clearValidate()
    },
    editUserForm(id) {
      if (id == null) {
        this.title = "新增用户"
        this.dialogFormVisible = true
      } else {
        userApi.getUserById(id).then(resp => {
          this.userForm = resp.data.user;
        });
        this.title = "修改用户"
        this.dialogFormVisible = true;
      }
    },
    handleSizeChange(val) {
      this.searchModel.pageSize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      this.searchModel.pageNo = val;
      this.getUserList();
    },
    search() {
      this.getUserList()
    },
    getUserList() {
      userApi.getUserList(this.searchModel).then(resp => {
        this.userList = resp.data.rows;
        this.total = resp.data.total;
      })
    },

    deleteUserById(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(resp => {
        userApi.deleteUserById(id).then(resp => {
          this.$message({
            message: resp.message,
            type: 'success'
          })
          this.getUserList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      })
    },
    getRoleAllList() {
      roleApi.getAllRoleList().then(resp => {
        this.roleList = resp.data;
        console.log(this.roleList)
      })
    }
  },
  created() {
    this.getUserList()
    this.getRoleAllList()
  }
}
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}

.el-input {
  margin-right: 30px;
}

</style>
